package com.tentative.competition.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.tentative.competition.common.exception.ServiceException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClientUtil {

    private static final Long sleepTime = 0L;

//    private static String referer = "https://offer.1688.com/offer/manage.htm?show_type=valid&tracelog=work_1_m_orderManage";

    public static JSONObject get(String url, JSONObject headerJson) {
        JSONObject json = null;
        try {
//            Thread.sleep(sleepTime);
            json = JSONObject.parseObject(getStr(url,headerJson));
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("cookie异常，请刷新1688平台页面重新校验一下");
        }
        return json;
    }

    public static String getStr(String url, JSONObject headerJson) {
        String result = "";
        try {
            Thread.sleep(sleepTime);
            GetMethod getMethod = new GetMethod(url);
            for (String key : headerJson.keySet()) {
                getMethod.setRequestHeader(key, headerJson.getString(key));
            }
            HttpClient httpClient = new HttpClient();
            httpClient.executeMethod(getMethod);
            result = getMethod.getResponseBodyAsString() ;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("cookie异常，请刷新1688平台页面重新校验一下");
        }
        return result;
    }

    public static String postStr(String url, JSONObject headerJson,JSONObject bodyJson) {
        String result = "";
        try {
            Thread.sleep(sleepTime);
            PostMethod postMethod = new PostMethod(url);
            for (String key : headerJson.keySet()) {
                postMethod.setRequestHeader(key, headerJson.getString(key));
            }
            for (String key : bodyJson.keySet()) {
                postMethod.setParameter(key, bodyJson.getString(key));
            }
//            NameValuePair[] parametersBody = new NameValuePair[bodyJson.size()];
//            int i = 0;
//            for (String key : bodyJson.keySet()) {
//                parametersBody[i++] = new NameValuePair(key, bodyJson.getString(key));
//            }
//            postMethod.setRequestBody(parametersBody);
            HttpClient httpClient = new HttpClient();
            httpClient.executeMethod(postMethod);
            result = postMethod.getResponseBodyAsString() ;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("cookie异常，请刷新1688平台页面重新校验一下");
        }
        return result;
    }


    public static String postStr(String url, JSONObject headerJson,JSONObject paramJson,JSONObject bodyJson) {
        String result = "";
        try {
            Thread.sleep(sleepTime);
            PostMethod postMethod = new PostMethod(url);
            for (String key : headerJson.keySet()) {
                postMethod.setRequestHeader(key, headerJson.getString(key));
            }
            for (String key : bodyJson.keySet()) {
                postMethod.setParameter(key, bodyJson.getString(key));
            }
//            NameValuePair[] parametersBody = new NameValuePair[bodyJson.size()];
//            int i = 0;
//            for (String key : bodyJson.keySet()) {
//                parametersBody[i++] = new NameValuePair(key, bodyJson.getString(key));
//            }
//            postMethod.setRequestBody(parametersBody);
            HttpClient httpClient = new HttpClient();
            httpClient.executeMethod(postMethod);
            result = postMethod.getResponseBodyAsString() ;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("cookie异常，请刷新1688平台页面重新校验一下");
        }
        return result;
    }

    public static JSONObject postJson(String url, JSONObject headerJson, JSONObject bodyJson) {
        String result = "";
        try {
            Thread.sleep(sleepTime);
            PostMethod postMethod = new PostMethod(url);
            for (String key : headerJson.keySet()) {
                postMethod.setRequestHeader(key, headerJson.getString(key));
            }
            for (String key : bodyJson.keySet()) {
                postMethod.setParameter(key, bodyJson.getString(key));
            }
//            NameValuePair[] parametersBody = new NameValuePair[bodyJson.size()];
//            int i = 0;
//            for (String key : bodyJson.keySet()) {
//                parametersBody[i++] = new NameValuePair(key, bodyJson.getString(key));
//            }
//            postMethod.setRequestBody(parametersBody);
            HttpClient httpClient = new HttpClient();
            httpClient.executeMethod(postMethod);
            result = postMethod.getResponseBodyAsString() ;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("cookie异常，请刷新1688平台页面重新校验一下");
        }
        return JSONObject.parseObject(result);
    }



    public static JSONObject restPostJson(String url, JSONObject headerJson, JSONObject bodyJson) {
        try {
            Thread.sleep(sleepTime);
            // 构建请求头信息
            HttpHeaders httpHeaders = new HttpHeaders();
            for (String key : headerJson.keySet()) {
                httpHeaders.set(key, headerJson.getString(key));
            }
//            httpHeaders.set("Content-Type", "application/x-www-form-urlencoded");
            RestTemplate restTemplate = new RestTemplate();
            // 封装请求参数
            LinkedMultiValueMap<String, Object> linkedMultiValueMap = new LinkedMultiValueMap<>();
            for (String key : bodyJson.keySet()) {
                linkedMultiValueMap.add(key,bodyJson.getString(key));
            }
            // 构建请求体
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(linkedMultiValueMap, httpHeaders);
            // 发起http请求, 以字节流接收响应信息, 方便解码特殊的响应头(例如响应头为"Content-Language/zh-CN")
            byte[] bytes = restTemplate.postForObject(url, httpEntity, byte[].class);
            // u8解码
            try {
                String result = new String(bytes, "UTF-8");
                return JSONObject.parseObject(result);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送post请求
     * @param reqUrl 请求url
     * @param jsonStr 字符串
     * @param tokenDto 相关配置信息
     * @return
     * @throws Exception
     */
    public static String sendHttpForJSON(String reqUrl, JSONObject headerJson, JSONObject bodyJson,String contentType) {
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            /**
             * 设置请求属性
             */
            // 设置请求方式为 POST
            httpConn.setRequestMethod("POST");
            // 设置请求数据格式，如 json 形式
            httpConn.setRequestProperty("Content-Type", contentType);
            // 设置接收数据格式，如 json 形式
            httpConn.setRequestProperty("Accept", "application/json");
            // 对于 post 请求，参数要放在 http 正文内，因此需要设为 true
            httpConn.setDoOutput(true);
            // 设置连接超时时间，单位为毫秒
            httpConn.setConnectTimeout(30 * 1000);
            // 设置读取超时时间，单位为毫秒
            httpConn.setReadTimeout(30 * 1000);
            // 设置长连接，但是这个需要 http 1.1 协议及服务端支持才会真正生效
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            /**
             * 设置header头部信息
             */
            for (String key : headerJson.keySet()) {
                httpConn.setRequestProperty(key, headerJson.getString(key));
            }
            /**
             * 设置 post 请求体参数
             */
            if (bodyJson != null) {
                OutputStream os = httpConn.getOutputStream();
                byte[] input = bodyJson.toString().getBytes("utf-8");
                os.write(input, 0, input.length);
                os.flush();
                os.close();
            }
            StringBuilder response = new StringBuilder();
            String inputLine;
            BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
            String responseStr = response.toString();
            //状态码
            int responseCode = httpConn.getResponseCode();
            //判断状态码是否请求正常
            if ( HttpURLConnection.HTTP_OK== httpConn.getResponseCode() ) {
//                String responseMessage = httpConn.getResponseMessage();
                return responseStr;
            }else {
                return null;
            }
        } catch (Exception throwable) {
            System.out.println("请求失败,异常信息:"+throwable);
            throwable.printStackTrace();
        }
        return null;
    }


    /**
     * 发送post请求
     * @param reqUrl 请求url
     * @param jsonStr 字符串
     * @param tokenDto 相关配置信息
     * @return
     * @throws Exception
     */
    public static String sendGetHttpForJSON(String reqUrl, JSONObject headerJson) {
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            /**
             * 设置请求属性
             */
            // 设置请求方式为 POST
            httpConn.setRequestMethod("GET");
            // 设置请求数据格式，如 json 形式
//            httpConn.setRequestProperty("Content-Type", contentType);
//            // 设置接收数据格式，如 json 形式
//            httpConn.setRequestProperty("Accept", "application/json");
            // 对于 post 请求，参数要放在 http 正文内，因此需要设为 true
            httpConn.setDoOutput(true);
            // 设置连接超时时间，单位为毫秒
            httpConn.setConnectTimeout(30 * 1000);
            // 设置读取超时时间，单位为毫秒
            httpConn.setReadTimeout(30 * 1000);
            // 设置长连接，但是这个需要 http 1.1 协议及服务端支持才会真正生效
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            /**
             * 设置header头部信息
             */
            for (String key : headerJson.keySet()) {
                httpConn.setRequestProperty(key, headerJson.getString(key));
            }
            StringBuilder response = new StringBuilder();
            String inputLine;
            BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
            String responseStr = response.toString();
            //状态码
            int responseCode = httpConn.getResponseCode();
            //判断状态码是否请求正常
            if ( HttpURLConnection.HTTP_OK== httpConn.getResponseCode() ) {
//                String responseMessage = httpConn.getResponseMessage();
                return responseStr;
            }else {
                return null;
            }
        } catch (Exception throwable) {
            System.out.println("请求失败,异常信息:"+throwable);
            throwable.printStackTrace();
        }
        return null;
    }



    public static String restPostStr(String url, JSONObject headerJson, JSONObject bodyJson) {
        try {
            Thread.sleep(sleepTime);
            // 构建请求头信息
            HttpHeaders httpHeaders = new HttpHeaders();
            for (String key : headerJson.keySet()) {
                httpHeaders.set(key, headerJson.getString(key));
            }
//            httpHeaders.set("Content-Type", "application/x-www-form-urlencoded");
            RestTemplate restTemplate = new RestTemplate();
            // 封装请求参数
            LinkedMultiValueMap<String, Object> linkedMultiValueMap = new LinkedMultiValueMap<>();
            for (String key : bodyJson.keySet()) {
                linkedMultiValueMap.add(key,bodyJson.getString(key));
            }
            // 构建请求体
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(linkedMultiValueMap, httpHeaders);
            // 发起http请求, 以字节流接收响应信息, 方便解码特殊的响应头(例如响应头为"Content-Language/zh-CN")
            byte[] bytes = restTemplate.postForObject(url, httpEntity, byte[].class);
            // u8解码
            try {
                String result = new String(bytes, "UTF-8");
                return result;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }




    public static String restPostStr2(String url, JSONObject headerJson, JSONObject bodyJson) {
        try {
            Thread.sleep(sleepTime);
            // 构建请求头信息
            HttpHeaders httpHeaders = new HttpHeaders();
            for (String key : headerJson.keySet()) {
                httpHeaders.set(key, headerJson.getString(key));
            }
            RestTemplate restTemplate = new RestTemplate();
            // 封装请求参数
            LinkedMultiValueMap<String, Object> linkedMultiValueMap = new LinkedMultiValueMap<>();
            for (String key : bodyJson.keySet()) {
                linkedMultiValueMap.add(key,bodyJson.getString(key));
            }
            // 构建请求体
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(linkedMultiValueMap, httpHeaders);
            // 发起http请求, 以字节流接收响应信息, 方便解码特殊的响应头(例如响应头为"Content-Language/zh-CN")
            byte[] bytes = restTemplate.postForObject(url, httpEntity, byte[].class);
            // u8解码
            try {
                String result = new String(bytes, "UTF-8");
                return result;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) throws IOException {
//        CloseableHttpResponse httpResponse = null;
//        HttpGet httpGet = new HttpGet("https://work.1688.com/?spm=a2638g.u_0_1001.framenav.du_6641_7377e.5d881768we0ZGI&_path_=sellerPro/2017sellerbase_offer/orderManage");
//        httpResponse =
//        org.apache.http.HttpEntity entity = httpResponse.getEntity();
//        System.out.println(httpResponse.getStatusLine());
//        System.out.println("response content:" + EntityUtils.toString(entity,"utf-8"));

    }


}
